package ro.upt.ac.cstaicu.execution.testng;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.testng.TestNG;

import ro.upt.ac.cstaicu.execution.CustomClassLoader;
import ro.upt.ac.cstaicu.execution.Executor;
import ro.upt.ac.cstaicu.execution.TestResult;
import ro.upt.ac.cstaicu.instrumentation.Instrumentor;
import ro.upt.ac.cstaicu.instrumentation.logging.GlobalLogger;

public class TestNGFacade implements Executor {
	
	
	private ArrayList<TestResult> results = new ArrayList<TestResult>();
	private GlobalLogger logger;
	private Instrumentor instrumentationModule;
	private Collection<String> ignoredTests;
	private CustomClassLoader cl;

	public TestNGFacade(Instrumentor instrumentationModule,
			GlobalLogger logger, Collection<String> ignoredTests) {
		this.ignoredTests = ignoredTests;
		this.instrumentationModule = instrumentationModule;
		this.logger = logger;
	}

	//TODO code duplication --> template method 
	public void executeTestClass(File[] classPathEntries, String projectClassPath, String className) {
		TestNG executor = new TestNG();
		
		cl = new CustomClassLoader(classPathEntries, projectClassPath, TestNG.class.getClassLoader(), instrumentationModule, logger, ignoredTests);

		executor.addClassLoader(cl);
		
		try {
			
			Class<?> testClass = cl.loadClass(className);
//			System.out.println(testClass.getMethods().length);
			TestNGListener listener = new TestNGListener();
			
			executor.addListener(listener);
			
			executor.setTestClasses(new Class[] {testClass});
			
			executor.run();
			
			results.addAll(listener.getResults());

			
//			Result res = junit.run(testClass);

			// TODO use polymorphism/composition
//			PredicateCounterLogger.getInstance().setRunningTime(
//					res.getRunTime());

//			results.addAll(listener.getResults());
	
		} catch (ClassNotFoundException e) {
			// TODO catch exception
			System.out.println(e);
		} 
	}
	
	@Override
	public ArrayList<TestResult> getTestResults() {
		// TODO Auto-generated method stub
		return results;
	}

	@Override
	public void clean() {
		cl.clearHistory();
		
	}
	
	 

}
